using System;
using System.Collections.Generic;
using CGF;
using LitJson;
using UnityEngine;
using UnityEngine.UI;
public class Table : MonoBehaviour
{
    public delegate string Column(RectTransform cell, JsonData data);
    public delegate string ColumnPro(JsonData data);

    public int colCount = 6;
    public ScrollView scrollView;
    public GameObject empty;

    private List<JsonData> listData = new List<JsonData>();
    private int pageSize = 20, page, totalPage;
    private string api, listKey, startDate, endDate;
    private Column[] columns;
    private Action<JsonData> onClickCell;
    private Action<Network.Res> onAPIRes;

    void Awake()
    {
        scrollView.SetCellUpdateCallback<RectTransform>(OnCellUpdate);
        scrollView.SetScrollToEndCallback(() =>
        {
            if (page < totalPage)
            {
                page++;
                ReqData(page);
            }
        });
    }

    void OnCellUpdate(RectTransform cell, int index)
    {
        bool useRefer = cell.GetComponent<Reference>();
        JsonData data = listData[index];
        for (int i = 0; i < colCount; i++)
        {
            Transform child = useRefer ? cell.Get<Transform>(i) : cell.GetChild(i);
            child.GetComponent<Text>().text = columns[i](cell, data);
            CButton btn = cell.GetComponent<CButton>();
            btn.SetClick(() => { onClickCell?.Invoke(data); });
            btn.enabled = onClickCell != null;
        }
    }

    public void ReqData(string api, string listKey, Column[] columns, string startDate = null, string endDate = null, Action<JsonData> onClickCell = null, Action<Network.Res> onAPIRes = null)
    {
        this.api = api;
        this.startDate = startDate;
        this.endDate = endDate;
        this.listKey = listKey;
        this.columns = columns;
        this.onClickCell = onClickCell;
        this.onAPIRes = onAPIRes;
        listData.Clear();
        page = 1;
        ReqData(page);
    }

    private async void ReqData(int page)
    {
        Network.Res res;
        string separator = api.Contains("?") ? "&" : "?";
        string url = $"{api}{separator}limit={pageSize}&page={page}";
        if (startDate != null)
        {
            if (!startDate.Contains(":"))
            {
                startDate += " 00:00:00";
            }
            url += $"&start_date={startDate}";
        }
        if (endDate != null)
        {
            if (!endDate.Contains(":"))
            {
                endDate += " 23:59:59";
            }
            url += $"&end_date={endDate}";
        }
        res = await Network.Get(url);
        onAPIRes?.Invoke(res);
        if (!res.success) return;
        JsonData data = res.jsonData["data"];
        totalPage = data.IsObject && data.Contains("totalCount") ? Mathf.CeilToInt((int)data["totalCount"] / (float)pageSize) : 1;
        JsonData list = string.IsNullOrEmpty(listKey) ? data : data[listKey];
        if (list != null)
        {
            for (int i = 0; i < list.Count; i++)
            {
                listData.Add(list[i]);
            }
        }
        scrollView.SetTotalNumber(listData.Count);
        empty.SetActive(listData.Count == 0);
        if (page == 1)
        {
            scrollView.ScrollToHead();
        }
    }

    public void SetData(List<JsonData> listData, Column[] columns)
    {
        this.listData = listData;
        this.columns = columns;
        scrollView.SetTotalNumber(listData.Count);
        empty.SetActive(listData.Count == 0);
    }
}
